package com.aofeng.hybrid.orm;

import android.content.Context;

import com.aofeng.hybrid.util.LogUtil;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库元数据
 * Created by LGY on 2016-06-27.
 */
public class DBMeta implements Serializable{

    private static DBMeta instance;

    /**
     * 实体表对应关系
     */
    public Map<String, String> entityTableNameMap = new HashMap<String, String>();

    /**
     * 表 元数据 对应关系
     */
    private Map<String, EntityMeta> map = new HashMap<String, EntityMeta>();

    public EntityMeta getEntityMeta(String tableName) {
        return map.get(tableName);
    }

    private DBMeta()
    {
    }

    public static DBMeta getMeta(Context context)
    {
        if(instance == null) {
            instance = reaDBdMeta(context);
        }
        return instance;
    }

    public void addTableNameMapping(String entity, String table)
    {
        entityTableNameMap.put(entity, table);
    }

    public void addEntity(String table, EntityMeta meta)
    {
        map.put(table, meta);
    }

    public void saveDBMeta(Context context) throws Exception{
        String path = context.getFilesDir().getAbsolutePath()+ File.separator + "orm.json";
        Gson gson = new Gson();
        String json = gson.toJson(this);
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path)));
            bw.write(json);
        } finally {
            if(bw != null)
                bw.close();
        }
    }

    private static DBMeta reaDBdMeta(Context context) {
        try {

            String path = context.getFilesDir().getAbsolutePath() + File.separator + "orm.json";
            File file = new File(path);
            if (!file.exists())
                return new DBMeta();

            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String json = "";
                String line;
                while ((line = br.readLine()) != null)
                    json += line;
                Gson gson = new Gson();
                return gson.fromJson(json, DBMeta.class);
            } finally {
                if(br != null)
                    br.close();
            }
        } catch (Exception e) {
            LogUtil.d("DBMeta", "读orm配置异常。");
            return new DBMeta();
        }
    }

    public void clearMeta() {
        entityTableNameMap = new HashMap<String, String>();
        map = new HashMap<String, EntityMeta>();
    }
}
